<template>
  <div class="app-main-content-box">
    <div class="index-dialog">
      <span class="text-dialog">首页弹窗</span>
      <el-button class="add-dialog" @click="toDialog">新增弹窗</el-button>
      <!-- 搜索 -->
      <div class="dialog-search">
        <el-form
          :inline="true"
          ref="filterForm"
          :rules="rules"
          size="small"
          :model="filterForm"
        >
          <el-form-item>
            <el-input
              placeholder="请输入标题"
              v-model.trim="filterForm.title"
              style="width: 250px"
              @keyup.enter.native="searchFn"
            />
          </el-form-item>
          <el-form-item>
            <el-select
              placeholder="请选择弹窗类型"
              filterable
              v-model="filterForm.popType"
            >
              <!-- <el-option label="请选择弹窗类型" value="all"></el-option> -->
              <!-- <el-option label="普通弹窗" :value="1"></el-option>
              <el-option label="储值弹窗" :value="2"></el-option> -->
              <el-option
                v-for="item in typeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select placeholder="请选择状态" v-model="filterForm.popState">
              <!-- <el-option label="请选择状态" value="all"></el-option> -->
              <el-option
                v-for="item in stateOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-date-picker
              v-model="validDate"
              :clearable="false"
              align="center"
              :default-time="['00:00:00', '23:59:59']"
              type="datetimerange"
              range-separator="~"
              value-format="yyyy-MM-dd HH:mm:ss"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            >
            </el-date-picker>
          </el-form-item>

          <el-form-item>
            <template>
              <el-button type="primary" size="small" @click="searchFn"
                >搜索</el-button
              >
              <el-button size="small" @click="resetForm('filterForm')"
                >重置</el-button
              >
            </template>
          </el-form-item>
        </el-form>
      </div>

      <!-- 表格 -->
      <div class="list-table">
        <el-table
          size="medium"
          border
          :data="list"
          stripe
          style="width: 100%"
          empty-text="暂无数据"
        >
          <el-table-column prop="title" align="center" label="标题" />
          <el-table-column prop="popType" align="center" label="弹窗类型">
            <template v-slot="scope">
              <span v-if="scope.row.popType === 1">普通弹窗</span>
              <span v-if="scope.row.popType === 2">储值弹窗</span>
            </template>
          </el-table-column>
          <el-table-column prop="imgUrl" align="center" label="弹窗图">
            <template v-slot="scope">
              <el-popover placement="right" title="" trigger="click">
                <img
                  slot="reference"
                  style="max-width: 50px"
                  :src="fileBaseUrl + scope.row.imgUrl"
                  alt=""
                />

                <img
                  :src="fileBaseUrl + scope.row.imgUrl"
                  alt=""
                  style="max-width: 800px"
                />
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column prop="insideParams" align="center" label="站内链接">
            <template v-slot="scope">
              <span>{{ JSON.parse(scope.row.insideParams).remark }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="showRule" align="center" label="显示设置">
            <template v-slot="scope">
              <span v-if="scope.row.showRule === 0">每次进入程序显示</span>
              <span v-if="scope.row.showRule > 0"
                >{{ scope.row.showRule }}天显示一次</span
              >
            </template>
          </el-table-column>
          <el-table-column prop="readTimes" align="center" label="查阅量" />
          <el-table-column prop="validDate" align="center" label="有效期">
            <template slot-scope="scope">
              <span
                >{{
                  $dateFtt('yyyy-MM-dd hh:mm', new Date(scope.row.startTime))
                }}
                ~
                {{
                  $dateFtt('yyyy-MM-dd hh:mm', new Date(scope.row.endTime))
                }}</span
              >
            </template>
          </el-table-column>
          <el-table-column prop="popState" align="center" label="状态">
            <template v-slot="scope">
              <span v-if="scope.row.popState === 1">未开始</span>
              <span v-if="scope.row.popState === 2">进行中</span>
              <span v-if="scope.row.popState === 3">已结束</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作">
            <template v-slot="scope">
              <el-button
                type="text"
                size="small"
                @click="editFn(scope.row.id, scope.row.popState)"
                :disabled="
                  scope.row.popState === 3 ||
                  new Date(scope.row.endTime).getTime() <= new Date().getTime
                    ? true
                    : false
                "
                >编辑</el-button
              >
              <el-button type="text" size="small" @click="checkFn(scope.row.id)"
                >查看</el-button
              >
              <el-button
                type="text"
                size="small"
                @click="delFn(scope.row.id)"
                :disabled="
                  scope.row.popState === 2 ||
                  scope.row.popState === 3 ||
                  new Date(scope.row.startTime).getTime() <= new Date().getTime
                    ? true
                    : false
                "
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <pagination-direction
          v-if="paginationConfig.total !== 0"
          :config="paginationConfig"
          @sizeschange="sizesChange"
          @pagechange="pageChange"
          :current-page.sync="paginationConfig.page"
          :page-sizes="paginationConfig.pageSizes"
        />
      </div>
    </div>
  </div>
</template>

<script>
import { getMarketingPopConfigList, delPopById } from '@/api/marketing'
import { mapGetters } from 'vuex'
export default {
  data() {
    return {
      loading: false,
      tableLoading: false,
      srcList: [],
      validDate: [],
      // 筛选
      filterForm: {
        title: '',
        popType: '',
        popState: '',

        startTime: '',
        endTime: ''
      },
      rules: {
        title: [
          { min: 1, max: 10, message: '长度在1到10之间', trigger: 'blur' }
        ]
      },
      list: [],
      // 分页配置
      paginationConfig: {
        direction: 'center', // 分页位置
        layout: 'total, sizes, prev, pager, next, jumper', // 分页类型
        pageSizes: [10, 20], // 分页pages
        total: 0,
        page: 1, // 页数-默认1
        pageSize: 10 // 每页条数-默认10
      },
      // 配置筛选选项
      typeOptions: [
        {
          value: 1,
          label: '普通弹窗'
        },
        {
          value: 2,
          label: '储值弹窗'
        }
      ],
      stateOptions: [
        {
          value: 1,
          label: '未开始'
        },
        {
          value: 2,
          label: '进行中'
        },
        {
          value: 3,
          label: '已结束'
        }
      ]
    }
  },
  watch: {
    searchSelect(val) {}
  },

  mounted() {
    this.curPage = Number(localStorage.getItem('curPage')) || 1
    this.initData(this.curPage)
    localStorage.removeItem('curPage')
  },

  computed: {
    ...mapGetters(['fileBaseUrl', 'curMenu'])
  },
  methods: {
    toDialog() {
      this.$nextTick(() => {
        this.curMenu[this.curMenu.length - 1] = {
          ...this.curMenu[this.curMenu.length - 1],
          title: '新增弹窗'
        }
        this.$store.dispatch(
          'setCurmenu',
          JSON.parse(JSON.stringify(this.curMenu))
        )
      })
      this.$router.push({
        path: '/marketing/activity-dialog-edit',
        query: { pageType: 'add', name: 'MarketingActivityDialogAdd' }
      })
    },
    async initData(
      page = this.paginationConfig.page,
      pageSize = this.paginationConfig.pageSize
    ) {
      this.filterForm.pageNum = page
      this.filterForm.pageSize = pageSize
      const params = Object.assign({}, this.filterForm)
      // 清除多余字段
      for (const key in params) {
        if (params[key] === '' || params[key] === 'all') {
          delete params[key]
        }
      }
      this.tableLoading = true

      const res = await getMarketingPopConfigList(params)
      this.list = res.data.list
      this.paginationConfig.total = res.data.total
      this.paginationConfig.page = res.data.pageNum
    },

    // 删除弹窗
    async delFn(id) {
      // 二次提醒
      await this.$confirm('是否确定删除当前弹窗内容', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true,
        roundButton: true
      })
      this.loading = true

      // 解决删除当前页最后一条信息时没显示数据
      const totalPage = Math.ceil(
        (this.paginationConfig.total - 1) / this.paginationConfig.pageSize
      )
      this.paginationConfig.page =
        this.paginationConfig.page > totalPage
          ? totalPage
          : this.paginationConfig.page
      this.paginationConfig.page =
        this.paginationConfig.page < 1 ? 1 : this.paginationConfig.page
      // 发请求
      await delPopById(id)
      // 提示
      this.$notify({
        title: '成功',
        message: '删除成功',
        type: 'success',
        duration: 2000,
        offset: 40
      })
      // 更新列表
      this.initData()
    },

    // 搜索
    searchFn() {
      this.filterForm.startTime = this.validDate[0]
      this.filterForm.endTime = this.validDate[1]
      this.loading = false
      this.paginationConfig.page = 1
      this.initData()
    },

    // 重置
    resetForm(formName) {
      ;(this.filterForm = {
        title: '',
        popType: '',
        popState: '',
        validDate: []
      }),
        (this.validDate = '')
      this.$refs[formName].resetFields()
      this.initData(1)
    },

    // 分页sizes改变
    sizesChange() {
      this.initData()
    },

    // 分页page改变
    pageChange() {
      this.initData()
    },

    // 跳转
    checkFn(id) {
      this.$nextTick(() => {
        this.curMenu[this.curMenu.length - 1] = {
          ...this.curMenu[this.curMenu.length - 1],
          title: '查看弹窗'
        }
        this.$store.dispatch(
          'setCurmenu',
          JSON.parse(JSON.stringify(this.curMenu))
        )
      })
      localStorage.setItem('curPage', this.paginationConfig.page.toString())
      this.$router.push({
        path: '/marketing/activity-dialog-edit',
        query: { pageType: 'check', id, name: 'MarketingActivityDialogCheck' }
      })
    },
    editFn(id, popState) {
      localStorage.setItem('curPage', this.paginationConfig.page.toString())
      this.$router.push({
        path: '/marketing/activity-dialog-edit',
        query: {
          pageType: 'edit',
          id,
          popState,
          name: 'MarketingActivityDialogEdit'
        }
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.text-dialog {
  margin-right: 20px;
}
.dialog-search {
  margin-top: 18px;
  .el-form--inline {
    .el-form-item {
      margin-right: 20px;
    }
  }

  .el-button--small {
    display: inline-block;
    padding: 9px 25px;
  }
}
</style>
